package com.nanachi.feign.core.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author yuhongtai
 * 查询服务列表组件
 */
@Component
public class ServerUrlTable {

    private final DiscoveryClient discoveryClient;

    private final Map<String, List<String>> serverUrlMap = new HashMap<>();

    @Autowired
    public ServerUrlTable(DiscoveryClient discoveryClient) {
        this.discoveryClient = discoveryClient;
        updateServerUrlMap();
    }



    /**
     * 每5s更新一次服务列表
     */
    @Scheduled(fixedRate = 5 * 1000)
    public void updateServerUrlMap() {
        discoveryClient.getServices().forEach(serviceName -> {
            List<ServiceInstance> instanceList = discoveryClient.getInstances(serviceName);
            List<String> newTargetUrls = instanceList.stream().map(
                    // 如果用了https
                    instance -> instance.isSecure() ?
                            "https://" + instance.getHost() + ":" + instance.getPort() :
                            "http://" + instance.getHost() + ":" + instance.getPort()
            ).collect(Collectors.toList());
            serverUrlMap.put(serviceName, newTargetUrls);
        });
    }

    /**
     * 根据服务名称，返回服务的列表
     *
     * @param serviceName 服务名称
     * @return 服务url集合
     */
    public List<String> get(String serviceName) {
        return serverUrlMap.getOrDefault(serviceName, null);
    }


}
